<?php

namespace app\process;

use support\Cache;
use support\Request;
use Webman\Push\Api;
use Workerman\Crontab\Crontab;
use plugin\admin\app\model\WorldResource;

class World
{
    public $data = [];

    public function onWorkerStart()
    {
        $resource = WorldResource::query()->where('status', 1)->get();

        /*foreach($resource as $k=>$item) {
            $this->data['resource_name'][$k] = $item->name;
            $this->data['resource_value'][$k] = $item->value;
            $this->data['resource_add'][$k] = $item->add;
            $this->data['resource_status'][$k] = $item->status;
        }*/

        // 初始化
        // dump('world start init...');
        foreach($resource as $item) {
            Cache::set($item->name, $item->init_value);
        }

        dump('stone设置的值为' . Cache::get('stone'));
        dump('tree设置的值为' . Cache::get('tree'));
        dump('water设置的值为' . Cache::get('water'));

        // stone+1, tree+1
        new Crontab('*/1 * * * * *', function() {
            Cache::set('tree', Cache::get('tree')+1);
            Cache::set('stone', Cache::get('stone')+2);
            Cache::set('water', Cache::get('water')+5);
        });

        new Crontab('*/1 * * * * *', function () {
            $api = new API(
                'http://127.0.0.1:3232',
                config('plugin.webman.push.app.app_key'),
                config('plugin.webman.push.app.app_secret')
            );
            // $api->trigger('world', 'data', [
            //     'resource_name' => $this->data['resource_name'],
            //     'resource_value' => $this->data['resource_name'],
            //     'resource_add' => $this->data['resource_add'],
            //     'resource_status' => $this->data['resource_status'],
            // ]);
            $api->trigger('world', 'resource', [
                'stone' => Cache::get('stone'),
                'tree' => Cache::get('tree'),
                'water' => Cache::get('water'),
            ]);
            dump('开始通信');
            dump('stone设置的值为' . Cache::get('stone'));
            dump('tree设置的值为' . Cache::get('tree'));
            dump('water设置的值为' . Cache::get('water'));
        });
    }
}